<?php
/**
 * 
 * Enter description here ...
 * @author jaspermutsaerts
 *
 */
class LengthValidator extends Validator
{
	protected $minLength;
	protected $maxLength;
	
	public function __construct($required = true, $minLength, $maxLength)
	{
		parent::__construct($required);
		$this->minLength = min($minLength, $maxLength);
		$this->maxLength = max($minLength, $maxLength);		
	}
	
	public function validate(Validatable $field)
	{
		if($this->required)
		{
			if(!parent::validate($field))
			{
				return false;
			}
			
		}
		$length = strlen($field->getValue());
		
		if($this->required || ($length > 0 && !is_null($field->getValue())))
		{
			if($length < $this->minLength || $length > $this->maxLength)
			{
				$field->setError('mag minimaal '.$this->minLength.' en maximaal '.$this->maxLength .' tekens bevatten');
				return false;
			}
		}
		return true;
	}
	
}